<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Home extends CI_Controller {
	public function index(){
		if($this->session->userdata('user_id') == '' || $this->session->userdata('user_name') == ''){
			$this->load->helper(array('url'));
			redirect('/user/login', 'location', 301);
		}
		else{			
			//===============================			
			#$this->session->userdata('user_id').'|'.$this->session->userdata('user_name');
			$this->layout->setLayout('default');
			$this->layout->setTitle('Administrator | Home');
				
			if(isset($_GET['date'])){
				$arrDate = explode("-", $_GET['date']);
				$month = $arrDate[0].'-'.$arrDate[1];
			}else{
				$year = isset($_GET['year']) ? $_GET['year'] : date('Y');
				$month = isset($_GET['month']) ? $year . '-'.str_pad(quotes_to_entities($_GET['month']), 2, "0", STR_PAD_LEFT) : date('Y-m');
				if ($year == "") $year = date('Y');
				if ($_GET['month'] == "") $month = $year . "-" . date('m');
			}
			$arrDate = explode("-", $month);
			$data['month'] = $arrDate[1].'-'.$arrDate[0];
			//Tinh so ngay trong thang
			$day = cal_days_in_month(CAL_GREGORIAN, $arrDate[1],$arrDate[0]);
			//===================================
			$sqlwebsite = "SELECT @row := @row + 1 AS STT, B.id_reg, U.user_name, SUM(B.mid_SMS) AS mid_SMS, SUM(B.mid_earm) AS mid_earm, SUM(B.bot_sms) as bot_sms, SUM(B.bot_earm) as bot_earm, (Sum(B.mid_earm) + Sum(B.bot_earm)) as Total
			FROM (SELECT  T.id_reg, count(T.phone) AS mid_SMS, Sum(T.sms_cost) AS mid_earm, '0' as bot_sms, '0' as bot_earm
			FROM `sms_user_mo` T
			WHERE  1=1 AND T.receive_date BETWEEN '" . $month . "-01 00:00:00' AND '" . $month . "-15 23:59:59'
			GROUP BY T.id_reg
			Union
			SELECT  T.id_reg, '0' AS mid_SMS, '0' AS mid_earm, count(T.phone) as bot_sms, Sum(T.sms_cost) as bot_earm
			FROM `sms_user_mo` T
			WHERE  1=1 AND T.receive_date BETWEEN '" . $month . "-16 00:00:00' AND '". $month . "-" . $day . " 23:59:59'
			GROUP BY T.id_reg
			) B
			INNER JOIN `sms_user` U On U.user_id_reg = B.id_reg, (Select @row := 0) R
			GROUP BY id_reg";
			$monthQuery = $this->db->query($sqlwebsite);
			if ($monthQuery->num_rows() > 0){
				$arrData = array();
				foreach ($monthQuery->result_array() as $row){					
					$data['items2'][] = $row;
					$total += intval($row['Total']);
				}
			}			
			$data['str_date'] = $strDate;		
			$data['earn_this_month'] = $total;
			//$data['month_now'] = $sql;
			
			
			$this->layout->view(THEME_DIR.'/home_index', $data);
		}
	}
}